﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Radzen;
using TuLing.IServices;
using TuLing.Services;

namespace TuLing.Maui
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                });

            builder.Services.AddMauiBlazorWebView();
            builder.Services.AddRadzenComponents();
#if DEBUG
            builder.Services.AddBlazorWebViewDeveloperTools();
    		builder.Logging.AddDebug();
#endif

            builder.Services.AddScoped<IRBACUserService, RBACUserService>();
            builder.Services.AddScoped<IRBACRoleService, RBACRoleService>();
            builder.Services.AddScoped<IRBACPermissionService, RBACPermissionService>();
            builder.Services.AddScoped<IRBACUserRoleService, RBACUserRoleService>();
            builder.Services.AddScoped<IRBACRolePermissionService, RBACRolePermissionService>();

            builder.Services.AddScoped<ICustomerService, CustomerService>();

            builder.Services.AddScoped<IProductCategoryService, ProductCategoryService>();
            builder.Services.AddScoped<IProductService, ProductService>();
            builder.Services.AddScoped<IProductUnitService, ProductUnitService>();

            builder.Services.AddScoped<IBuyOrderService, BuyOrderService>();
            builder.Services.AddScoped<IBuyOrderReturnService, BuyOrderReturnService>();
            builder.Services.AddScoped<IBuyOrderDetailService, BuyOrderDetailService>();

            builder.Services.AddScoped<ISaleOrderService, SaleOrderService>();
            builder.Services.AddScoped<ISaleOrderReturnService, SaleOrderReturnService>();
            builder.Services.AddScoped<ISaleOrderDetailService, SaleOrderDetailService>();

            builder.Services.AddScoped<ISupplierService, SupplierService>();
            builder.Services.AddScoped<IFinanceService, FinanceService>(); 
            
            var folder = Environment.SpecialFolder.LocalApplicationData;
            var path = Environment.GetFolderPath(folder);
            var dbPath = Path.Join(path, "database.db3");
            builder.Services.AddDbContext<DefaultDbContext>(options => options.UseSqlite($"Data Source={dbPath}").EnableSensitiveDataLogging());

            // 获取 DbContext 并尝试迁移（仅调试用）
            using var scope = builder.Services.BuildServiceProvider().CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            dbContext.Database.Migrate(); // 自动应用迁移

            return builder.Build();
        }
    }
}
